<template>
  <div class="box">
    <div class="btn">
      <el-button type="primary" plain size="small" @click="add" icon="el-icon-upload2">上传</el-button>
    </div>

    <el-table
      :data="tableData"
      style="width: 100%">
      <el-table-column
        prop="id"
        label="ID">
      </el-table-column>
      <el-table-column
        prop="title"
        label="名称">
      </el-table-column>
      <el-table-column
        prop="file_type"
        label="文件类型">
      </el-table-column>
      <el-table-column
        prop="size"
        label="大小(kb)">
      </el-table-column>
      <el-table-column
        prop="publisher"
        label="发布人">
      </el-table-column>
      <el-table-column
        prop="create_time"
        label="发布时间">
      </el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="danger"
            @click="handleDelete(scope.row)">删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="currentPage"
      :page-sizes="pageSizes"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total">
    </el-pagination>
    <el-dialog :title="title" :visible.sync="dialogFormVisible" @close="clearInfo">
      <el-form :model="form" :rules="rules" ref="dialogForm">
        <el-form-item label="标题" :label-width="formLabelWidth" prop="title">
          <el-input v-model="form.title" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="资源类型" :label-width="formLabelWidth" prop="file_type">
          <el-select v-model="form.file_type" placeholder="请选择类型" style="width: 100%">
            <el-option label="视频" value="video"></el-option>
            <el-option label="文本" value="text"></el-option>
            <el-option label="压缩包" value="zip"></el-option>
            <el-option label="图片" value="picture"></el-option>
            <el-option label="其它" value="other"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="视频封面" :label-width="formLabelWidth" v-if="form.file_type=='video'">
          <el-upload
            class="upload-demo"
            ref="coverUpload"
            :limit="1"
            action=""
            :accept=accept
            :http-request="coverUpload"
            list-type="text">
            <el-button size="small" type="primary">点击上传</el-button>
          </el-upload>
          <!--          进度条-->
          <el-progress :percentage="coverPercentage" v-show="coverPercentage"></el-progress>
        </el-form-item>
        <el-form-item label="选择资源" :label-width="formLabelWidth">
          <el-upload
            class="upload-demo"
            ref="upload"
            :limit="1"
            action=""
            :http-request="customUpload"
            list-type="text">
            <el-button size="small" type="primary">点击上传</el-button>
          </el-upload>
          <el-progress :percentage="percentage" v-show="percentage"></el-progress>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="upload">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import * as qiniu from 'qiniu-js'
import {getQiNiuToken, sourceDelete, sourcePage, uploadSource} from "@/api/sources";

export default {
  name: 'index',
  data() {
    return {
      uptoken: {
        token: '',
        key: ""
      },
      percentage: 0,
      coverPercentage: 0,
      accept: "image/jpeg,image/gif,image/png,image/bmp",
      title: '上传',
      tableData: [],
      multipleSelection: [],
      currentPage: 1,
      pageSizes: [5, 10, 15, 20],
      pageSize: 5,
      total: 0,
      rules: {
        title: [
          {required: true, message: '请输入资源名称', trigger: 'blur'},
        ],
        file_type: [
          {required: true, message: '请选择资源类型', trigger: 'blur'}
        ]
      },
      formLabelWidth: '80px',
      dialogFormVisible: false,  //  控制对话框的显示隐藏
      form: {
        title: '',
        file_type: '',
        cover_key: '', // 视频封面
        key: '',   // 视频资源
        size: '',
      }
    }
  },
  methods: {
    // 删除
    handleDelete(row) {
      this.$confirm('此操作将永久删除该数据, 是否继续?', '删除', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {   // 确定
        let {id} = row
        // 发送异步请求
        sourceDelete(id).then(response => {
          this.$notify.success(response.message)
          this.sourcePageData()
        })
      })
    },
    // 上传
    add() {
      this.dialogFormVisible = true
    },
    upload() {
      uploadSource(this.form).then(response => {
        this.$notify.success(response.message)
        this.dialogFormVisible = false
        this.sourcePageData()
      })
    },
    coverUpload(data) {
      getQiNiuToken().then(res => {
        const token = res.token
        const key = res.key + "." + data.file.name.split('.').reverse()[0]
        this.form.cover_key = key
        const putExtra = {};
        const config = {}
        const observable = qiniu.upload(data.file, key, token, putExtra, config)
        const that = this
        const observer = {
          next(res) {
            that.coverPercentage = Math.floor(res.total.percent)
          },
          error(err) {
            // 上传失败
          },
          complete(res) {
            // 上传完成
          }
        }
        const subscription = observable.subscribe(observer) // 上传开始
      })


    },
    // 默认传递参数
    customUpload(data) {
      getQiNiuToken().then(res => {
        const token = res.token
        // data.file.name    a.txt     20250725024733.txt    20250725024733.jpg
        const key = res.key + "." + data.file.name.split('.').reverse()[0]
        // 动态添加form对象的属性  size
        this.form.size = Math.floor(data.file.size / 1024)
        // 动态添加form对象的属性  key   七牛云资源名字
        this.form.key = key
        const putExtra = {};
        const config = {}
        const observable = qiniu.upload(data.file, key, token, putExtra, config)
        const that = this
        const observer = {
          // 上传过程中 会实时回调该函数 res.total.percent
          next(res) {
            console.log(this)
            that.percentage = Math.floor(res.total.percent)
          },
          error(err) {
            // 上传失败
          },
          complete(res) {
            // 上传完成
          }
        }
        const subscription = observable.subscribe(observer) // 上传开始
      })
    },
    handleSizeChange(val) {
      this.pageSize = val
      this.sourcePageData()
    },
    handleCurrentChange(val) {
      this.currentPage = val
      this.sourcePageData()
    },
    //关闭弹窗时 清除表单数据
    clearInfo() {
      this.form = {
        title: '',
        file_type: '',
        cover_key: '',
        key: '',
        size: '',
      }
      this.percentage = 0
      this.coverPercentage = 0
      this.$refs.dialogForm.clearValidate()
      this.$refs.upload.clearFiles();
      this.$refs.coverUpload.clearFiles();
    },
    sourcePageData() {
      sourcePage({page: this.currentPage, size: this.pageSize}).then(
        response => {
          this.total = response.total
          this.tableData = response.table_data
        }
      )
    },
  },
  created() {
    this.sourcePageData()
  }
}
</script>
<style scoped lang="scss">
.box {
  padding: 20px;
  box-sizing: border-box;
  margin-top: 50px;
}

.btn {
  margin-bottom: 10px;
}

</style>

